﻿#region License information
/*
 * Smart Include
 *  
 * Copyright (c) 2014 Fredrik Schultz
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * Project website: http://kaliko.com/smart-include/
 */
#endregion

namespace Kaliko.SmartInclude {
    using System.Collections.Generic;
    using System.IO;
    using System.IO.Compression;
    using System.Web;

    internal class JavascriptMinifier {

        /// <summary>
        /// Checks if the original files have been changed since the last compiled script
        /// file was created. If they have been changed, all the files are collected and 
        /// minified into two files. One that is minified and one that's after being 
        /// minified also is compressed with GZip (which use less bandwidth but are 
        /// transparently uncompressed in most modern browsers).
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        internal static string MinifyScripts(List<string> files) {
            // Get a unique hash based on the requested files. This will 
            // be used for naming the combined scripts on the server.
            string hash = Common.GetStringHash(files);

            string filepath = Config.IncludeFilePath;
            string filename = hash + ".js";
            HttpServerUtility server = HttpContext.Current.Server;

            if (Common.HaveFilesBeenChanged(files, filename, filepath)) {
                MemoryStream stream = new MemoryStream();
                StreamWriter writer = new StreamWriter(stream);

                // Combine and minify all scripts requested
                foreach (string file in files) {
                    if(File.Exists(server.MapPath(file))) {
                        FileStream infile = new FileStream(server.MapPath(file), FileMode.Open, FileAccess.Read, FileShare.Read);
                        writer.Write(Yahoo.Yui.Compressor.JavaScriptCompressor.Compress(new StreamReader(infile, System.Text.Encoding.UTF8).ReadToEnd(), true, true, false, false, -1, System.Text.Encoding.UTF8, System.Globalization.CultureInfo.CurrentCulture));
                        writer.Flush();
                        infile.Close();
                    }
                }

                // Temporary fix to handle issue of missing last character in gzip stream
                writer.Write("// EOF");
                writer.Flush();

                // Save to minified file
                FileStream outfile = new FileStream(filepath + filename, FileMode.Create, FileAccess.Write, FileShare.Write);
                stream.WriteTo(outfile);
                outfile.Close();

                // Save the minified file as a gzip archive
                outfile = new FileStream(filepath + filename + ".gz", FileMode.Create);
                GZipStream compressedzipStream = new GZipStream(outfile, CompressionMode.Compress, true);
                stream.WriteTo(compressedzipStream);
                
                compressedzipStream.Close();
                outfile.Close();

                writer.Close();
                stream.Close();
            }


            string datestamp = Common.GetFileDateHash(filepath + filename);

            return string.Format("<script src=\"{0}Get.aspx?v={1}&d={2}&t=js\" type=\"text/javascript\"></script>", Config.IncludePath, hash, datestamp);
        }

    }
}
